package com.clstu.reflection;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class Reflection01 {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\re.properties"));
        String classfullpath = properties.getProperty("classfullpath");
        String method = properties.getProperty("method");

        //得到Class对象
        Class cls = Class.forName(classfullpath);
        Object o = cls.newInstance();//实例
        Method method1 = cls.getMethod(method);//方法对象
        method1.invoke(o);

//        Field name = cls.getField("name");//报错,不能得到私有的成员属性
        Field age = cls.getField("age");//得到属性对象,(此时它只是一个属性对象,不能直接使用)
        System.out.println(age.get(o));//跟o.getAge()恰恰相反,age.get(o),这就是反射机制

        Constructor constructor = cls.getConstructor();//得到构造器,(无参构造器)
        Constructor constructor1 = cls.getConstructor(String.class);//得到构造器,有参构造器 String.class 表示的是String类的class对象
        System.out.println(constructor1);
        System.out.println(constructor);

    }
}
